package cn.yhp.mybatis.binding;

import cn.hutool.core.lang.ClassScanner;
import cn.yhp.mybatis.session.Configuration;
import cn.yhp.mybatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author yhp
 * @description Mapper接口映射器注册机【将所有mapper接口包装到mapper工厂对象中，便于创建对应的mapper代理对象】
 * @date 2023/11/8
 */
public class MapperRegistry {

    private Configuration configuration;

    public MapperRegistry(Configuration configuration){
        this.configuration=configuration;
    }

    /**
     * 将mapper接口和对应的mapper工厂添加进Map
     */
    private final Map<Class<?>,MapperProxyFactory<?>> knownMappers=new HashMap<>();

    /**
     * 获取mapper接口代理对象
     * @param type
     * @param sqlSession
     * @return
     * @param <T>
     */
    public <T> T getMapper(Class<T> type, SqlSession sqlSession){
        MapperProxyFactory<T> mapperProxyFactory =(MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null){
            throw new RuntimeException("Type "+type+"在MapperRegistry中没有注册");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        }catch (Exception e){
            throw new RuntimeException("获取Mapper代理对象异常",e);
        }
    }

    public <T> boolean hasMapper(Class<T> type){
        return knownMappers.containsKey(type);
    }

    /**
     * 注册Mapper接口
     * @param type
     * @param <T>
     */
    public <T> void addMapper(Class<T> type){
        // 需是接口才可注册
        if (type.isInterface()){
            if (hasMapper(type)){
                throw new RuntimeException("Type "+type+"在MapperRegistry中已经注册过");
            }
            // 注册mapper映射器代理工厂
            knownMappers.put(type,new MapperProxyFactory<>(type));
        }
    }

    /**
     * 将某包下的mapper接口注册
     * @param packageName
     */
    public void addMappers(String packageName){
        Set<Class<?>> mapperSet = ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }

}
